package com.example.administrator.wallet.view.activity.asset;

import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.wallet.MainActivity;
import com.example.administrator.wallet.R;
import com.example.administrator.wallet.adapter.QueryCoinAdapter;
import com.example.administrator.wallet.base.BaseActivity;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.AddCoinBean;
import com.example.administrator.wallet.model.bean.QueryCoinBean;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;

public class QueryCoinActivity extends BaseActivity {

    @Bind(R.id.ed_query)
    EditText edQuery;
    @Bind(R.id.cancel)
    TextView cancel;
    @Bind(R.id.mList)
    ListView mList;
    @Bind(R.id.activity_query_coin)
    LinearLayout activityQueryCoin;
    @Bind(R.id.delete_all)
    ImageView deleteAll;
    @Bind(R.id.content)
    TextView content;
    @Bind(R.id.load)
    ImageView load;

    private String temp;
    private IRequestManager manager;
    private String token;
    private Gson mGson;
    private QueryCoinBean queryCoinBean;
    private List<QueryCoinBean.DataBean> mDatas;
    private QueryCoinAdapter iAdapter;
    private AddCoinBean addCoinBean;
    private Intent mIntent;
    private int top;
    private int index;
    private Animation hyperspaceJumpAnimation;
    private Animation alphaAnimatal;

    @Override
    public void init() {
        content.setVisibility(View.VISIBLE);
        setStatuColor();
        setEditTextInhibitInputSpeChat(edQuery);
        manager = RequestFactory.getReqequestManager();
        token = SharedPrefsUtil.getValue(QueryCoinActivity.this, "wallet", "token", null);
        mGson = new Gson();
        mDatas = new ArrayList<>();

        initListener();
    }

    private void initListener() {
        edQuery.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                temp = charSequence.toString();
                if (i2 > 0) {
                    deleteAll.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (token != null && temp != null && !(temp.equals(""))) {
                    hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                            context, R.anim.load_animation);
                    // 使用ImageView显示动画
                    content.setVisibility(View.GONE);
                    load.setVisibility(View.VISIBLE);
                    load.startAnimation(hyperspaceJumpAnimation);
                    httpRequest();
                }
            }
        });
    }

    private void httpRequest() {
        manager.httpPost(Api.BaseUrl + Api.query_coin, Api.getQueryCoin(token, temp), new IRequestCallback() {
            @Override
            public void onSuccess(String Response) {
                queryCoinBean = mGson.fromJson(Response, QueryCoinBean.class);
                if (queryCoinBean.getCode() == 200) {
                    mDatas = queryCoinBean.getData();
                    initAdapter();
                    if (iAdapter.getCount() > 0) {
                        alphaAnimatal = AnimationUtils.loadAnimation(
                                context, R.anim.hide_img);
                        // 使用ImageView显示动画
                        load.setVisibility(View.VISIBLE);
                        load.startAnimation(alphaAnimatal);
                        load.setVisibility(View.GONE);
                    }
                } else {
                    Toast.makeText(QueryCoinActivity.this, queryCoinBean.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String error) {
                Log.e("TAG", error);
            }
        });
    }

    private void initAdapter() {
        iAdapter = new QueryCoinAdapter(QueryCoinActivity.this, mDatas);
        mList.setAdapter(iAdapter);


        iAdapter.position(new QueryCoinAdapter.OnClickPosition() {
            @Override
            public void getPosition(QueryCoinBean.DataBean bean) {
                String symbol = bean.getSymbol();
                String token_addr = bean.getToken_addr();
                String unit = bean.getUnit();
                String icon = bean.getIcon();
                manager.httpPost(Api.BaseUrl + Api.add_coin, Api.setAddCoin(token, symbol, icon, unit, token_addr), new IRequestCallback() {
                    @Override
                    public void onSuccess(String Response) {
                        addCoinBean = mGson.fromJson(Response, AddCoinBean.class);
                        if (addCoinBean.getCode() == 200) {
                            mIntent = new Intent(QueryCoinActivity.this, MainActivity.class);
                            mIntent.putExtra("hide", 1);
                            startActivity(mIntent);
                        } else {
                            Toast.makeText(QueryCoinActivity.this, addCoinBean.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onFailure(String error) {
                        Log.e("TAG", error);
                    }
                });
            }
        });
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_query_coin;
    }

    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText
     */
    public static void setEditTextInhibitInputSpeChat(EditText editText) {

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat = "[ `~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？0123456789]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (matcher.find()) return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }


    @OnClick({R.id.ed_query, R.id.cancel, R.id.delete_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ed_query:
                break;
            case R.id.cancel:
                finish();
                break;
            case R.id.delete_all:
                edQuery.setText("");
                break;
        }
    }


}
